package org.pi.common.plot.figures

import scala.swing.event._

class SwingFigure extends javax.swing.JPanel 
with org.pi.common.plot.figures.BaseFigure 
with org.pi.common.gui.helper.MouseInteractionsImpl 
{
	/** private this pointer */
	private val self = this
	/** private temp. variable for the currently selected point.x */
	private var sx: Int = 0;
	/** private temp. variable for the currently selected point.y */
	private var sy: Int = 0;

	//
	// popup menu and actions
	//
	private val popup = new javax.swing.JPopupMenu();
	private val copyFigure2clipMenuItem = new javax.swing.JMenuItem("copy figure as bitmap 2 clipboard");
	private val copyAxes2clipMenuItem = new javax.swing.JMenuItem("copy axes as bitmap 2 clipboard");
	private val resetZoomMenuItem = new javax.swing.JMenuItem("reset zoom");
	popup.add(copyFigure2clipMenuItem)
	popup.add(copyAxes2clipMenuItem)
	popup.add(resetZoomMenuItem)

	// copy figure as bitmap
	copyFigure2clipMenuItem.addActionListener(new java.awt.event.ActionListener() {
		def actionPerformed(e: java.awt.event.ActionEvent): Unit = {
			copyFigureAsBitmapToClipboard()
		}
	});
	// copy figure as bitmap
	copyAxes2clipMenuItem.addActionListener(new java.awt.event.ActionListener() {
		def actionPerformed(e: java.awt.event.ActionEvent): Unit = {
			val index = getAxesIndex(sx, sy)
			if (index>=0) {
				copyAxesAsBitmapToClipboard(index)
			}
		}
	});

	// reset the zoom
	resetZoomMenuItem.addActionListener(new java.awt.event.ActionListener() {
		def actionPerformed(e: java.awt.event.ActionEvent): Unit = {
			val index = getAxesIndex(sx, sy)
			if (index>=0) {
				getAxes(index).resetZoom()
			}
		}
	});
	
	//
	// observer pattern implementation
	// (repaint if something changed in the figure)
	//
	addObserver(new org.pi.common.observerpattern.Observer {
		override def notifiedByObservable(obs: org.pi.common.observerpattern.Observable) : Unit = {
			repaint()
		}
	})

	//
	// init this panel
	//
	setMinimumSize(new java.awt.Dimension(90,90))
	setBackground(new java.awt.Color(1.0f,1.0f,0.8f)) 

	def copyFigureAsBitmapToClipboard() : Unit = {
		val w = getWidth(); //g0.getClipBounds().width;
		val h = getHeight(); //g0.getClipBounds().width;
		val I = new java.awt.image.BufferedImage((2*w), (2*h), java.awt.image.BufferedImage.TYPE_4BYTE_ABGR);
		val g = I.getGraphics().asInstanceOf[java.awt.Graphics2D];
		g.scale(2.0,2.0);
		paint(g);
		
		org.pi.common.gui.clipboard.Clipboard.copyImageToClipboard(I)
	}

	def copyAxesAsBitmapToClipboard(axesIndex: Int) : Unit = {
		val (w,h) = getAxesSizeInPixels(axesIndex)
		val I = new java.awt.image.BufferedImage((2*w.toInt), (2*h.toInt), java.awt.image.BufferedImage.TYPE_4BYTE_ABGR);
		val g = I.getGraphics().asInstanceOf[java.awt.Graphics2D];
		val graphics = g.create(0,0,2*w.toInt,2*h.toInt).asInstanceOf[java.awt.Graphics2D];
		graphics.setColor( getBackground() )
		graphics.fillRect(0, 0, 2*w.toInt, 2*h.toInt)
		graphics.scale(2.0,2.0);
		getAxes(axesIndex).paint(graphics);
		org.pi.common.gui.clipboard.Clipboard.copyImageToClipboard(I)
	}
	
	override def selectPoint(px: Int, py:Int, button: Int) : Unit = {
		super.selectPoint(px, py, button)
		val index = getAxesIndex(px, py)
		if (index>=0) {
			val (x,y) = getPositionForAxes(px, py, index)
			getAxes(index).selectPoint( x, y )
		}		
	}

	override def selectRegion(x1:Int, y1:Int, x2:Int, y2:Int) : Unit = {
		super.selectRegion(x1,y1,x2,y2)
		val index = getAxesIndex(x1, y1)
		if (index>=0) {
			val (ax1,ay1) = getPositionForAxes(x1, y1, index)
			val (ax2,ay2) = getPositionForAxes(x2, y2, index)
			getAxes(index).selectRegion( Math.min(ax1,ax2),Math.min(ay1,ay2),Math.max(ax1,ax2),Math.max(ay1,ay2) )
		}
	}

	override def callMenu(x1:Int, y1:Int) : Unit = {
		super.callMenu(x1,y1)
		sx = x1
		sy = y1
		popup.show(self,sx,sy);		
	}
	
	override def paintComponent(graphics1: java.awt.Graphics) : Unit = {
		super.paintComponent(graphics1);
		val ownGraphics = graphics1.create();
		ownGraphics.setClip(null);
		val graphics = ownGraphics.create(0,0,size.width,size.height).asInstanceOf[java.awt.Graphics2D];
        paintFigure(graphics)
	}

	override def activate() {
		//this.setVisible(true)
	}
}

object SwingFigure {
	
	def figure = {
		val fig = new SwingFigure()
	    val f = new javax.swing.JFrame();
		f.setLayout( new java.awt.BorderLayout() )
	    f.add(java.awt.BorderLayout.CENTER, fig)
	    f.addWindowListener(new java.awt.event.WindowAdapter{
	      override def windowClosing(event: java.awt.event.WindowEvent) {
	        f.dispose()
	      }
	    })
	    f.pack()
	    f.setSize(400,200)
	    f.setVisible(true)
	    fig
	}
	
	def main(args: Array[String]) {
		print("Test SwingFigure")
		val fig = figure
		var axes : org.pi.common.plot.axes.Axes = null 
		var line : org.pi.common.plot.drawables.Line = null 
		var j = 0
		while (j <2) {
		    axes = new org.pi.common.plot.axes.SimpleAxes()
		    axes.addDrawable( new org.pi.common.plot.drawables.Line(20,10,80,30) )
		    line = new org.pi.common.plot.drawables.Line(120,50,90,20) 
		    axes.addDrawable( line )
		    fig.subplot(2,1,j)
		    fig.setCurrentAxes(axes)
		    j += 1
		}
		org.pi.common.snippets.SimpleAction("setLW") {
			val r = new java.util.Random()
			line.lineWidth = r.nextFloat()*5+1;
			line.color = new java.awt.Color(r.nextFloat(),r.nextFloat(),r.nextFloat())
		}
		org.pi.common.snippets.SimpleAction("save") {
			fig.saveAs("testfigure.png")
		}
		org.pi.common.snippets.SimpleAction("clear") {
			axes.clear
		}
		org.pi.common.snippets.SimpleAction("addLine") {
			val r = new java.util.Random()
		    line = new org.pi.common.plot.drawables.Line(r.nextFloat()*200,r.nextFloat()*200,r.nextFloat()*200,r.nextFloat()*200) 
		    axes.addDrawable( line )
		}
	}
}